package com.wg.dome.handle;

import com.wg.dome.ClientPeer;
import com.wg.dome.ErrorCode;
import com.wg.dome.ErrorHelper;
import com.wg.dome.annotation.Request;
import com.wg.dome.attribute.Attribute;
import com.wg.dome.attribute.AttributeHelper;
import com.wg.dome.entity.config.InitEquipEntity;
import com.wg.dome.entity.user.EquipEntity;
import com.wg.dome.operation.OperationCode;
import com.wg.dome.operation.WearEquipRequest;
import com.wg.dome.operation.WearEquipResponse;
import com.wg.dome.repository.EquipRepositoryEx;
import com.wg.dome.repository.InitEquipRepository;
import com.wg.common.net.OperationRequest;
import com.wg.common.net.OperationResponse;
import com.wg.common.net.SendParameters;

/**
 * 穿装备
 */
@Request(OperationCode = OperationCode.WEAR_EQUIP)
public class HandleWearEquipRequest extends BaseHandle {

    @Override
    public OperationResponse execute(ClientPeer peer, OperationRequest request, SendParameters sendParameters) {
        WearEquipRequest wearEquipRequest = new WearEquipRequest(request);
        if (!wearEquipRequest.isValid()) {
            return ErrorHelper.getInvalidResponse(wearEquipRequest);
        }

        if (wearEquipRequest.getPlayerId() != peer.getPlayerId()) {
            return ErrorHelper.getErrorResponse(request.getOperationCode(),
                    ErrorCode.PLAYERID_MATCH_ERROR, wearEquipRequest.getPlayerId(), peer.getPlayerId());
        }

        EquipRepositoryEx equipRepository = new EquipRepositoryEx(peer.getPlayerId());
        EquipEntity wearEquip = equipRepository.getEntityFromPack(wearEquipRequest.getEquipId());
        if (wearEquip == null) {
            return ErrorHelper.getErrorResponse(request.getOperationCode(), ErrorCode.PACK_EQUIP_NOT_EXIST, wearEquipRequest.getEquipId());
        }

        InitEquipRepository initEquipRepository = new InitEquipRepository();
        InitEquipEntity initEquipEntity = initEquipRepository.get(wearEquip.getsId());
        if (initEquipEntity != null) {
            EquipEntity oldEquip = equipRepository.getEntity(wearEquipRequest.getSzPos(), initEquipEntity.getKind());
            if (oldEquip != null) {
                oldEquip.setPos((byte) 0);
                equipRepository.update(oldEquip);
            }
        }
        wearEquip.setPos(wearEquipRequest.getSzPos());
        equipRepository.update(wearEquip);

        Attribute attribute = AttributeHelper.getSignHeroAttribute(peer.getPlayerId(), wearEquipRequest.getSzPos());

        WearEquipResponse wearEquipResponse = new WearEquipResponse();
        wearEquipResponse.setSzPos(wearEquipRequest.getSzPos());
        wearEquipResponse.setEquipId(wearEquipRequest.getEquipId());
        wearEquipResponse.setSzAttribute(attribute.toHashTable());
        return new OperationResponse(request.getOperationCode(), wearEquipResponse);
    }
}
